package com.welsy.authoring.business
{
	import com.adobe.cairngorm.business.ServiceLocator;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	import com.welsy.authoring.event.GetTestEvent;
	import com.welsy.authoring.model.CourseModelLocator;
	import com.welsy.authoring.view.coursecomponents.ElementEditPanel;
	import com.welsy.authoring.view.coursecomponents.ElementIconView;
	import com.welsy.authoring.view.coursecomponents.ModuleEditPanel;
	import com.welsy.authoring.view.coursecomponents.ModuleIconView;
	import com.welsy.authoring.view.coursecomponents.TestEditPanel;
	import com.welsy.authoring.vo.CourseComponentsVO;
	import com.welsy.authoring.vo.CourseVO;
	import com.welsy.authoring.vo.course.ElementVO;
	import com.welsy.authoring.vo.course.ModuleVO;
	import com.welsy.authoring.vo.course.TestComponents;
	import com.welsy.authoring.vo.course.pattern.ICourseIterator;
	
	import flash.events.MouseEvent;
	import flash.net.*;
	
	import mx.containers.*;
	import mx.events.*;
	import mx.rpc.AbstractOperation;
	import mx.rpc.soap.*;
		
	public class CourseDao
	{
		private var elementDetailPanel:ElementEditPanel;		
		private var testDetailPanel:TestEditPanel;		
		private var moduleEditPanel:ModuleEditPanel;		
        private var modulePropertiesPanel:Canvas;
		
		private var myddu:DragAndDropUtils = new DragAndDropUtils;
						
		public function getCourseComponents (cc:CourseComponentsVO, area:VBox):void
		{				
			area.removeAllChildren();			
			var iterator:ICourseIterator = cc.iterator();
                                
			while(iterator.hasNext()) {
		    	//module
		    	var moduleVO:ModuleVO;
		    	moduleVO = ModuleVO(iterator.next())
		    	
		    	var module:ModuleIconView = ElementFactory.getModule ();
		    	module.addEventListener(DragEvent.DRAG_ENTER, myddu.doDragEnter);
	            module.addEventListener(DragEvent.DRAG_DROP, myddu.doDragDrop);
			    module.addEventListener(MouseEvent.MOUSE_MOVE, myddu.dragIt);
			    module.module = moduleVO;
                
                //modulehitarea
                var modulehitarea:Canvas = new Canvas;
      			modulehitarea.name = "modulehitarea";
   			    modulehitarea.width = 40;
   			    modulehitarea.height = 30;
   			    modulehitarea.setStyle('backgroundImage', 'assets/moduleGrip.gif');
  			    module.hitArea = modulehitarea;
			    module.mouseEnabled = false;
			    modulehitarea.addEventListener(MouseEvent.CLICK, moduleProperties);
         		module.addChild(modulehitarea);
         		
         		//elements
         		var elIterator:ICourseIterator = moduleVO.iterator();           
           		while(elIterator.hasNext()) {   
	           		
	           		var elementVO:ElementVO = ElementVO(elIterator.next());
	          		var myCanvas:ElementIconView;
	          			          		
	          		if ((elementVO.type == "0") || (elementVO.type  == "1"))
						myCanvas = ElementFactory.getEvaluationTest(int(elementVO.type ));
					else
						myCanvas = ElementFactory.getElement(int(elementVO.type ));
										
					myCanvas.element = elementVO;
					myCanvas.type = elementVO.type;
					myCanvas.testID = elementVO.testID;
					myCanvas.modulePosition = module.module.position;					
					
					if (elementVO.audioId != "0"){
    					var audio:ElementIconView = ElementFactory.getAudioElement();
        				audio.addEventListener(MouseEvent.MOUSE_MOVE, myddu.dragIt);
        				myCanvas.addChild(audio);
    				}
										
					myCanvas.addEventListener(DragEvent.DRAG_ENTER,myddu.doDragEnter);
		            myCanvas.addEventListener(DragEvent.DRAG_DROP,myddu.doDragDrop);
		            myCanvas.addEventListener(MouseEvent.MOUSE_MOVE, myddu.dragIt);
		            
		            if ((elementVO.type == "0") || (elementVO.type  == "1"))
		            	myCanvas.addEventListener(MouseEvent.CLICK, testProperties);
		            else
		            	myCanvas.addEventListener(MouseEvent.CLICK, elementProperties);

					module.addChild(myCanvas);
           		}
		    			    	                      
            	area.addChild(module);                 	    		
       		}		
		}	
		
		public function setElementProperties (myPP:ElementEditPanel):void {
        	 elementDetailPanel = myPP;         	 	 
        }	      
        
        public function setTestProperties (myPP:TestEditPanel):void {
        	 testDetailPanel = myPP;	 
        }
          
        public function setModuleProperties (myPP:ModuleEditPanel):void {
        	 moduleEditPanel = myPP;
        }     
                      
        public function testProperties (event:MouseEvent):void {
        	
        	//set properties for the test panel without using model
        	var testIconView : ElementIconView = ElementIconView(event.currentTarget);           	 	
           	var element:ElementVO = ElementVO(testIconView.element);  
           	testDetailPanel.element = element;           	
           	
           	//show test properties
        	testDetailPanel.setVisible(true);
        	
        	if (int(element.testID) > 0) {           	         	      	 	
	    	 	//invoke svc for retrieving test data
	    	 	var getTestEvent : GetTestEvent = new GetTestEvent(GetTestEvent.EVENT_GET_TEST);
	    	 	getTestEvent.testID = int(element.testID);			    	
	    	 	CairngormEventDispatcher.getInstance().dispatchEvent(getTestEvent);	     	 	
        	} else {
        		CourseModelLocator.getInstance().selectedTest = new TestComponents;
        	}
        	        
        } 
        
        public function elementProperties (event:MouseEvent):void {
			 
			 //set properties for the element panel without using model
			 var elementIconView : ElementIconView = ElementIconView(event.currentTarget); 			       	
        	 var element : ElementVO = ElementVO(elementIconView.element);
        	 element.type = elementIconView.type;
        	 elementDetailPanel.element = element;
           	 elementDetailPanel.setDefaults();           	           	 
           	 
           	 //show element properties
           	 elementDetailPanel.currentState = element.type;  
           	 elementDetailPanel.setVisible(true);
        	       	         	 
        }                
        
        public function moduleProperties (event:MouseEvent):void {        	 
        	 moduleEditPanel.setVisible(true);
        	 var moduleIconView : ModuleIconView = ModuleIconView(event.currentTarget.parent);
        	 moduleEditPanel.module = moduleIconView.module; 
        	 moduleEditPanel.setDefaults();           	           	 
        }
      
		 //todo da migliorare
         public function saveCourse(area:VBox, course:CourseVO):void {
        	var requestStruct:String = "<SaveCourseComponents  xmlns='http://Welsy.ServiceContracts/2007/02'>"; 
        	requestStruct += "<ns1:SaveCourseComponentsRequest  xmlns:ns1='http://tempuri.org/DataTypes.xsd'>";
			requestStruct += "<ns1:Course><ns1:CourseID>" + course.id + "</ns1:CourseID>";
			requestStruct += "<ns1:ParentCourseId>" + course.parentCourseId + "</ns1:ParentCourseId>";
			requestStruct += "<ns1:Title>" + course.title + "</ns1:Title>";
			requestStruct += "<ns1:TitleUser>" + course.titleUser + "</ns1:TitleUser>";
			requestStruct += "<ns1:Description>" + course.description + "</ns1:Description>";
			requestStruct += "<ns1:Credits>" + course.credits + "</ns1:Credits>";
			requestStruct += "<ns1:WebLink>" + course.webLink + "</ns1:WebLink>";
			requestStruct += "<ns1:Note>" + course.notes + "</ns1:Note>";
			requestStruct += "<ns1:State>" + course.state + "</ns1:State>";						
			requestStruct += "<ns1:AuthorID>" + course.authorId + "</ns1:AuthorID>";
			requestStruct += "<ns1:MapView>" + course.mapView + "</ns1:MapView>";
			requestStruct += "<ns1:NavigationMap>" + course.navigationMap + "</ns1:NavigationMap>";
			requestStruct += "<ns1:DurationTime>" + course.durationTime + "</ns1:DurationTime>";
			requestStruct += "<ns1:Target>" + course.target + "</ns1:Target>";
			requestStruct += "</ns1:Course><ns1:Modules>";
        	var myElementsVector:Array = area.getChildren();
        	var modulePos:int = 1;
        	
        	var cc:CourseComponentsVO = new CourseComponentsVO;
        	cc.course = course
        	cc.removeAllItems();
        	
        	for (var i:int = 0; i < myElementsVector.length; i++) {
				var myModule:Array = myElementsVector[i].getChildren();

				if (myModule.length > 1){
	        		var elemPos:int = 1;
	        		var moduleIcon:ModuleIconView = ModuleIconView (myElementsVector[i]);
	        		var module:ModuleVO = moduleIcon.module;
	        		module.removeAllItems();
	        			        		
	        		if (module.moduleId == null || module.moduleId == "")
	        			module.moduleId = "0";
	        		
	        		module.position = modulePos.toString();
	        		requestStruct += "<ns1:ModuleComponentsType>";
	        		requestStruct += "<ns1:Module>";
	        		requestStruct += "<ns1:ModuleID>" + module.moduleId + "</ns1:ModuleID>";
				    requestStruct += "<ns1:Title>" + module.title + "</ns1:Title>";
				    requestStruct += "<ns1:Position>" + modulePos + "</ns1:Position>";
				    requestStruct += "<ns1:DisplayFeedback>" + module.displayFeedback + "</ns1:DisplayFeedback>";
					requestStruct += "<ns1:Note>" + module.notes + "</ns1:Note>";
				    requestStruct += "</ns1:Module>";
				    requestStruct += "<ns1:Elements>";		        	        	
		        	            		        	
		        	for (var k:int = 1; k < myModule.length; k++) {
		        		var myElementIcon:ElementIconView = ElementIconView(myModule[k]);
		        		var myElement:ElementVO = ElementVO(myElementIcon.element);
		        		
		        		//set type based on icon type
		        		myElement.type = myElementIcon.type;
		        		
		        		if (myElement.elementId == null || myElement.elementId == "")
	        				myElement.elementId = "0";
	        			
	        			if (myElement.fileId == null || myElement.fileId == "")
	        				myElement.fileId = "0";
	        			
//	        			if (myElement.getChildren().length == 0)
//	        				myElement.audioId = "0";
	        				
	        			var audioId:String
	        			audioId = myElement.audioId;
	        				
						myElement.position = elemPos.toString()
		        		requestStruct += "<ns1:ElementType>";
		        		requestStruct += "<ns1:ElementID>" + myElement.elementId + "</ns1:ElementID>";
		        		requestStruct += "<ns1:Title>" + myElement.title + "</ns1:Title>";
		        		requestStruct += "<ns1:Type>" + myElement.type + "</ns1:Type>";
		        		requestStruct += "<ns1:Position>" + elemPos + "</ns1:Position>";
		        		requestStruct += "<ns1:ElementAudioID>" + audioId + "</ns1:ElementAudioID>";
		        		requestStruct += "<ns1:FileRepositoryId>" + myElement.fileId + "</ns1:FileRepositoryId>";
		        		requestStruct += "<ns1:Note>" + myElement.notes + "</ns1:Note>";    
	                    requestStruct += "<ns1:FileName>" + myElement.fileName + "</ns1:FileName>";
	                    requestStruct += "<ns1:NavigationType>" + myElement.navigationType + "</ns1:NavigationType>";
	                    requestStruct += "<ns1:TestId>" + myElement.testID + "</ns1:TestId>";
		        		requestStruct += "</ns1:ElementType>";	
		        		elemPos++;		
		        		
		        		//add element to the module		        		
		        		module.addItem(myElement);        		
		        	}
					
					//add module to the CourseComponentsVO
					cc.addItem(module);
	                
					requestStruct += "</ns1:Elements>";
					requestStruct += "</ns1:ModuleComponentsType>";
					modulePos++;									
				}
	        }
	        
	        requestStruct += "</ns1:Modules></ns1:SaveCourseComponentsRequest>";
	        requestStruct += "</SaveCourseComponents>";
	        var myInsertionRequest:XML = new XML (requestStruct);	        
	        
	        //todo adeguare a cairngorm
	        var ws : WebService = ServiceLocator.getInstance().getWebService("CourseService") as WebService
	        executeService (ws, "SaveCourseComponents", myInsertionRequest); 
	        	
	        //set courseComponents for updating UI 	        
	        CourseModelLocator.getInstance().selectedCourse = cc; 
	        
	        
        } 
        
        //todo da togliere
        public function executeService (wsBlogAggr:WebService, opName:String, message:XML) : void
        {
        	var myAbstractOperation:AbstractOperation = wsBlogAggr.getOperation(opName);
        	var myOperation:Operation = Operation (myAbstractOperation);
        	myOperation.request = message;   
        	wsBlogAggr[opName].send ();
        }
                
	}
}